var attachPolygonDataSource = undefined;
/*getAttachGeojson();*/
/*$(function(){
	setTimeout(function(){
		getAttachGeojson();
	},3000);
});*/


var dantihua = {
    appendToMenu: function (guid, name, cssName) {
        $("#gridsMenuContent .mCSB_container").append("<div data-id='" + guid + "' class='work-submenu-child'><div class='work-child-title'><i class='icon-grid' style='border-radius:4px; background:" + cssName + "'></i><span class='text'>" + name + "</span></div></div>");
    },
    getAttachGeojson: function () {
        //viewer.selectedEntityChanged.addEventListener(selectEntityChanged);
        //初始加载geojson
        var allDataSource = viewer.dataSources._dataSources;
        var isHaveAttach = false;
        for (var a = 0; a < allDataSource.length; a++) {
            if (allDataSource[a]._sourceUri) {
                if (allDataSource[a]._sourceUri.indexOf("attach.geojson") != -1) {
                    attachPolygonDataSource = allDataSource[a];
                    var entities = attachPolygonDataSource.entities.values;
                    var len = entities.length;
                    for (var i = 0; i < len; i++) {
                        var entity = entities[i];
                        if (entity.name != "高危楼房") {
                            entity.polygon.outline = false;
                            entity.polygon.perPositionHeight = false;
                            var aCss = "rgba(" + parseInt(255 * entity.polygon.material.color._value.red) + "," + parseInt(255 * entity.polygon.material.color._value.green) + "," + parseInt(255 * entity.polygon.material.color._value.blue) + ",1)";
                            entity.polygon.material = LSGlobe.Color.fromRandom({
                                red: entity.polygon.material.color._value.red,
                                green: entity.polygon.material.color._value.green,
                                blue: entity.polygon.material.color._value.blue,
                                alpha: 0.7
                            });


                            //计算中心点
                            if (!!entity.polygon.hierarchy._value.positions) {
                                var aPos = entity.polygon.hierarchy._value.positions;
                            } else {
                                var aPos = entity.polygon.hierarchy._value;
                            }

                            var iX = 0, iY = 0, iZ = 0;
                            for (var j = 0; j < aPos.length; j++) {
                                iX = aPos[j].x + iX;
                                iY = aPos[j].y + iY;
                                iZ = aPos[j].z + iZ;
                            }
                            iX = iX / aPos.length;
                            iY = iY / aPos.length;
                            iZ = iZ / aPos.length;

                            var WorlsPos = new LSGlobe.Cartesian3(iX, iY, iZ);
                            var oDegree = ellipsoid.cartesianToCartographic(WorlsPos);
                            var lat = LSGlobe.Math.toDegrees(oDegree.latitude);
                            var lng = LSGlobe.Math.toDegrees(oDegree.longitude);
                            var alt = oDegree.height;
                            if (i < 3) { alt = -15; }
                            var oLabelEntity = {
                                name: entity.name,
                                position: LSGlobe.Cartesian3.fromDegrees(lng, lat, alt + 40),
                                id: "label" + entity.id,
                                label: {
                                    text: entity.name,
                                    translucencyByDistance: new LSGlobe.NearFarScalar(1.5e2, 2.0, 1.5e7, 0.5),
                                    font: '25px Helvetica',
                                    fillColor: LSGlobe.Color.BLACK,
                                    outlineColor: LSGlobe.Color.BLACK,
                                    outlineWidth: 4,
                                    disableDepthTestDistance: 1000000000,
                                    scale: 0.5,
                                    showBackground: true,
                                    backgroundColor: new LSGlobe.Color.fromCssColorString("rgba(255, 255, 255, 0.8)"),
                                    backgroundPadding: new LSGlobe.Cartesian2(14, 10)
                                }
                            };
                            attachPolygonDataSource.entities.add(oLabelEntity);

                            var name = entity.name;
                            var id = entity.id;
                            //添加实体到单体化列表【图层管理】
                            dantihua.appendToMenu(id, name, aCss);
                        }
                    }

                    var DantihuaLen = $("#dantihua").children().length;
                    if (DantihuaLen <= 0) {
                        $("#dantihua").parents(".monomer").remove();
                    }
                    isHaveAttach = true;
                }
            }
        }
        if (!isHaveAttach) {
            var sTimeSecondes = new Date().getTime();
            var geojsonUrl = basePath + "/attach/" + dataGuid + "/attach.geojson?" + sTimeSecondes;
            var promise = LSGlobe.GeoJsonDataSource.load(geojsonUrl, {
                clampToGround: true,
                attachPolygon: true
            });
            promise.then(function (dataSource) {
                attachPolygonDataSource = dataSource;
                viewer.dataSources.add(dataSource);

                var entities = dataSource.entities.values;
                for (var i = 0; i < entities.length; i++) {
                    var entity = entities[i];
                    entity.polygon.outline = false;
                    entity.polygon.perPositionHeight = false;
                    var aCss = "rgba(" + parseInt(255 * entity.polygon.material.color._value.red) + "," + parseInt(255 * entity.polygon.material.color._value.green) + "," + parseInt(255 * entity.polygon.material.color._value.blue) + ",1)";
                    entity.polygon.material = LSGlobe.Color.fromRandom({
                        red: entity.polygon.material.color._value.red,
                        green: entity.polygon.material.color._value.green,
                        blue: entity.polygon.material.color._value.blue,
                        alpha: 0.7
                    });


                    //计算中心点
                    if (!!entity.polygon.hierarchy._value.positions) {
                        var aPos = entity.polygon.hierarchy._value.positions;
                    } else {
                        var aPos = entity.polygon.hierarchy._value;
                    }

                    var iX = 0, iY = 0, iZ = 0;
                    for (var j = 0; j < aPos.length; j++) {
                        iX = aPos[j].x + iX;
                        iY = aPos[j].y + iY;
                        iZ = aPos[j].z + iZ;
                    }
                    iX = iX / aPos.length;
                    iY = iY / aPos.length;
                    iZ = iZ / aPos.length;

                    var WorlsPos = new LSGlobe.Cartesian3(iX, iY, iZ);
                    var oDegree = ellipsoid.cartesianToCartographic(WorlsPos);
                    var lat = LSGlobe.Math.toDegrees(oDegree.latitude);
                    var lng = LSGlobe.Math.toDegrees(oDegree.longitude);
                    var alt = oDegree.height;
                    if (i < 3) { alt = -15; }
                    var oLabelEntity = {
                        name: entity.name,
                        position: LSGlobe.Cartesian3.fromDegrees(lng, lat, alt + 40),
                        id: "label" + entity.id,
                        label: {
                            text: entity.name,
                            translucencyByDistance: new LSGlobe.NearFarScalar(1.5e2, 2.0, 1.5e7, 0.5),
                            font: '25px Helvetica',
                            fillColor: LSGlobe.Color.BLACK,
                            outlineColor: LSGlobe.Color.BLACK,
                            outlineWidth: 4,
                            disableDepthTestDistance: 1000000000,
                            scale: 0.5,
                            showBackground: true,
                            backgroundColor: new LSGlobe.Color.fromCssColorString("rgba(255, 255, 255, 0.8)"),
                            backgroundPadding: new LSGlobe.Cartesian2(14, 10)
                        }
                    };
                    dataSource.entities.add(oLabelEntity);


                    var name = entity.name;
                    var id = entity.id;
                    //添加实体到单体化列表【图层管理】
                    dantihua.appendToMenu(id, name, aCss);
                }

                //attachPolygonDataSource = dataSource;

                var DantihuaLen = $("#dantihua").children().length;
                if (DantihuaLen <= 0) {
                    $("#dantihua").parents(".monomer").remove();
                }
            }).otherwise(function (error) {
                $("#dantihua").parents(".monomer").remove();
            });
        }
    },
    hideAttachPolygon: function () {
        //隐藏所有单体化面
        if (attachPolygonDataSource) {
            var entities = attachPolygonDataSource.entities.values;
            for (var i = 0; i < entities.length; i++) {
                var entity = entities[i];
                entity.polygon.material = LSGlobe.Color.fromRandom({
                    red: entity.polygon.material.color._value.red,
                    green: entity.polygon.material.color._value.green,
                    blue: entity.polygon.material.color._value.blue,
                    alpha: 0.01
                });
            }
        }
    }
}

function clickDth(entityId) {
    //隐藏单体化
	dantihua.hideAttachPolygon();
	var entity = attachPolygonDataSource.entities.getById(entityId);
	entity.polygon.material = LSGlobe.Color.fromRandom({
		red:entity.polygon.material.color._value.red,
		green:entity.polygon.material.color._value.green,
		blue:entity.polygon.material.color._value.blue,
        alpha : 0.7
    });
	var entityPosition = getRealPosition(entity);
    viewer.camera.flyTo({
        destination: LSGlobe.Cartesian3.fromDegrees(entityPosition.lng,entityPosition.lat,entityPosition.alt),
        duration: 3
    });
	/*viewer.flyTo(entity);*/
}
function getRealPosition(Entities){
    var aPos=Entities.polygon.hierarchy._value.positions;
    var iX=0,iY=0,iZ=0,maxX=0,maxY=0,minX,minY,realheight;
    for(var i=0;i<aPos.length;i++){
        iX=aPos[i].x+iX;
        iY=aPos[i].y+iY;
        iZ=aPos[i].z+iZ;
    }
    iX=iX/aPos.length;
    iY=iY/aPos.length;
    iZ=iZ/aPos.length;

    //中心点经纬度
    var WorlsPos=new LSGlobe.Cartesian3(iX,iY,iZ);
    var oDegree=ellipsoid.cartesianToCartographic(WorlsPos);
    var lng=LSGlobe.Math.toDegrees(oDegree.longitude);
    var lat=LSGlobe.Math.toDegrees(oDegree.latitude);
    for(var a=0;a<aPos.length;a++){
        //当前点的经纬度
        var sWorlsPos=new LSGlobe.Cartesian3(aPos[a].x,aPos[a].y,aPos[a].z);
        var sDegree=ellipsoid.cartesianToCartographic(sWorlsPos);
        var slng=LSGlobe.Math.toDegrees(sDegree.longitude);
        var slat=LSGlobe.Math.toDegrees(sDegree.latitude);
		//中心点经纬度
        var oPos = {"x":slng,"y":slat};
        var currentheight = viewAnalysis.getDistance(oPos, lng, lat);
        if(a==0){
            realheight=currentheight
		}
        if(realheight<currentheight){
            realheight=currentheight
        }
    }
	var sTileset=whichTileset(lng,lat);
    var alt=realheight*1.7320508075689+50 + sTileset._boundingSphere.center.z*1+sTileset.name.position.split(",")[2]*1;
    return {"lat":lat,"lng":lng,"alt":alt};
}

//单体化显示隐藏
$(document).on("click","#analysis-panel .layer-item.monomer .checkicon",function(){
    var oThis = $(this);
    if(oThis.hasClass("active")){
        oThis.removeClass("active");
        if(oThis.hasClass("box")){
            var oChilds = oThis.parent().next().find(".checkicon");
            var oChildChange = oThis.parent().next().find(".checkicon").removeClass("active");
            for(var a=0;a<oChilds.length;a++){
                var sGuid = oChilds.eq(a).parent().attr("id");
                attachPolygonDataSource.entities.getById(sGuid).show =false;
            }
        }else{
            var oParentChild = oThis.parents(".layer-item-content").children().length;
            var oParentBox = oThis.parents(".layer-item-content").find(".checkicon.active");
            if(oParentBox.length<=0){
                oThis.parents(".layer-item-content").prev().find(".checkicon").removeClass("active");
            }
            
            var sGuid = oThis.parent().attr("id");
            attachPolygonDataSource.entities.getById(sGuid).show =false;
        }
    }else{
        oThis.addClass("active");
        if(oThis.hasClass("box")){
            var oChilds = oThis.parent().next().find(".checkicon");
            var oChildChange = oThis.parent().next().find(".checkicon").addClass("active");
            for(var a=0;a<oChilds.length;a++){
                var sGuid = oChilds.eq(a).parent().attr("id");
                attachPolygonDataSource.entities.getById(sGuid).show =true;
            }
        }else{
            var oParentChild = oThis.parents(".layer-item-content").children().length;
            var oParentBox = oThis.parents(".layer-item-content").find(".checkicon.active");
            if(oParentChild==oParentBox.length){
                oThis.parents(".layer-item-content").prev().find(".checkicon").addClass("active");
            }
            var sGuid = oThis.parent().attr("id");
            attachPolygonDataSource.entities.getById(sGuid).show =true;
        }
    }

    return false;
});
function getRootPath ()
{
//    var curWwwPath = window.document.location.href;
//    var pathName = window.document.location.pathname;
//    var pos = curWwwPath.indexOf (pathName);
//    var localhostPaht = curWwwPath.substring (0, pos);
//    var projectName = pathName.substring (0, pathName.substr (1).indexOf ('/') + 1);
//    /*if(projectName=="/manage"){projectName="/"}
//    if(projectName=="/LSGlobe"){projectName="/"}*/
    //	return localhostPaht;
    return "http://59.111.95.231";
}